package com.zys.el.time.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zys.el.time.common.exception.CustomException;
import com.zys.el.time.common.exception.sql.SqlException;
import com.zys.el.time.dto.Page;
import com.zys.el.time.entity.Topic;
import com.zys.el.time.entity.User;
import com.zys.el.time.fegin.UserClient;
import com.zys.el.time.mapper.TopicMapper;
import com.zys.el.time.service.TopicService;
import com.zys.el.time.vojo.TopicVo;
import com.zys.el.time.vojo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic>
        implements TopicService {
    @Resource
    private UserClient userClient;

    @Override
    public Page<TopicVo> getPageByChannelId(Long channelId, Integer page, Integer size) {
        List<Topic> topics = this.baseMapper.getPageByChannelId(channelId, (page - 1) * size, size);

        List<Long> ids = topics.stream().map(Topic::getUserId).collect(Collectors.toList());
        // 获取发布者信息
        Map<Long, User> userMap = userClient.getUserListByBatchId(ids);

        // 封装更多的信息
        List<TopicVo> topicVoList = topics.stream().map(t -> {
            Long userId = t.getUserId();
            TopicVo vo = new TopicVo();
            BeanUtils.copyProperties(t, vo);
            vo.setOwner(new UserVo(userMap.get(userId)));
            return vo;
        }).collect(Collectors.toList());

        return new Page<>(page, topicVoList, size, topicVoList.size());
    }

    @Override
    public void addTopic(Topic topic) {
        if (topic.getTopicTitle() == null
                || topic.getChannelId() == null
                || topic.getUserId() == null) {
            throw new CustomException("传参不能为空");
        }
        boolean b = this.save(topic);
        if (!b) {
            throw new SqlException("添加话题失败");
        }
    }

}




